package cn.loveniu.microbitcar;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    //private Toolbar toolbar;
    private TextView status;
    private StringBuilder mstringbuilder;
    public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//没有用到
    BluetoothReceiver receiver;
    BluetoothAdapter mBtAdapter;
    BluetoothSocket mBtSocket;
    private BluetoothUtil client;
    private ListView mListView;
    private List<String> ListDevice;
    private ArrayAdapter<String> mAdapter;
    private Button mbutton, button_search;
    private EditText editText;
    private ProgressBar progressBar;

    //private LoopProgressBar loopProgressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取位置权限
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 10);
            }
        }

        //toolbar=(Toolbar)findViewById(R.id.toolbar);
        status = (TextView) findViewById(R.id.textView2);
        mListView = (ListView) findViewById(R.id.listView);
        mbutton = (Button) findViewById(R.id.button);
        button_search = (Button) findViewById(R.id.button_search);
        editText = (EditText) findViewById(R.id.editText);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setVisibility(View.INVISIBLE);
        //loopProgressBar=(LoopProgressBar)findViewById(R.id.loop);
        ListDevice = new ArrayList<String>();
        mstringbuilder = new StringBuilder();
        //setSupportActionBar(toolbar);
        enablebluetooth();
        mbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BluetoothUtil.WriteTask W = client.new WriteTask(editText.getText().toString());
                W.start();
            }
        });
        button_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBtAdapter.isEnabled()) {
                    show("蓝牙未开启");
                } else {
                    mBtAdapter.startDiscovery();
                    show("正在寻找设备");
                    progressBar.setVisibility(View.VISIBLE);
                }
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mBtAdapter.cancelDiscovery();//停止搜索
                progressBar.setVisibility(View.INVISIBLE);
                String str = ListDevice.get(position);
                String macAdress = str.split("\\|")[1];
                BluetoothDevice device = mBtAdapter.getRemoteDevice(macAdress);
                client = new BluetoothUtil(device, handler);
                try {
                    client.connect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 开启蓝牙且被发现
     */
    private void enablebluetooth() {
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
       /*if(!mBtAdapter.isEnabled()){这里可以先使能，可以在REQUEST_DISCOVERABLE处使能，这样的话可以连使能和请求被发现一块完成
          // mBtAdapter.enable();
           Intent enableIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
           startActivityForResult(enableIntent,REQUEST_ENABLE);
       }
       else {
           show("蓝牙已开启");
       }*/
        Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivityForResult(enable, REQUEST_DISCOVERABLE);
    }

    /**
     * 销毁事件，注销广播
     */
    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BluetoothUtil.CONNECT_FAILED:
                    show("连接失败");
                    try {
                        client.connect();
                    } catch (Exception e) {
                        Log.e("TAG", e.toString());
                    }
                    break;
                case BluetoothUtil.CONNECT_SUCCESS:
                    show("连接成功");
                    mListView.setVisibility(View.INVISIBLE);
                    break;
                case BluetoothUtil.READ_FAILED:
                    show("读取失败");
                    break;
                case BluetoothUtil.WRITE_FAILED:
                    show("写入失败");
                    break;
                case BluetoothUtil.DATA:
                    mstringbuilder.append(msg.obj.toString());
                    show(mstringbuilder.toString());
                    break;
            }
        }
    };

    /**
     * 请求响应结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
          /* case REQUEST_ENABLE:
               if(requestCode!= Activity.RESULT_OK){
                 show("蓝牙未开启");
               }
               else
                   show("蓝牙已开启");
               break;*/
            case REQUEST_DISCOVERABLE:
                if (resultCode == Activity.RESULT_CANCELED) {
                    show("蓝牙未开启");
                } else
                    show("蓝牙已开启");
                break;
            default:
                break;
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.menu,menu);
        return true;
    }

    private static final int REQUEST_ENABLE = 1;
    private static final int REQUEST_DISCOVERABLE = 2;

    /**
     * 注册广播事件
     */
    @Override
    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        receiver = new BluetoothReceiver();
        registerReceiver(receiver, filter);
        IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter2);
        //Toast.makeText(MainActivity.this, "receiver注册成功", Toast.LENGTH_SHORT).show();
    }

    /**
     * 广播
     */
    private class BluetoothReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Toast.makeText(MainActivity.this, "响应广播回调函数", Toast.LENGTH_SHORT).show();
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //show("搜索到设备了");
                //System.out.println("搜索到设备了");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String str = device.getName() + "|" + device.getAddress();
                if (ListDevice.indexOf(str) == -1)// 防止重复添加
                    ListDevice.add(str); // 获取设备名称和mac地址
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
                showDevices();
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                progressBar.setVisibility(View.INVISIBLE);
                show("搜索完成");
                //System.out.println("搜索结束");
            }

        }
    }

    ;

    /**
     * 菜单栏点击事件
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
//            case R.id.search:
//                if(!mBtAdapter.isEnabled()){
//                    show("蓝牙未开启");
//                }
//                else {
//                    mBtAdapter.startDiscovery();
//                    show("正在寻找设备");
//                    progressBar.setVisibility(View.VISIBLE);
//                }
//                break;
////            case R.id.about:
////                Toast.makeText(MainActivity.this,"关于我们",Toast.LENGTH_SHORT).show();
////                break;
            default:
        }
        return true;
    }

    private void showDevices() {
        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                ListDevice);
        mListView.setAdapter(mAdapter);
    }

    /**
     * 更新UI方法
     *
     * @param string
     */
    private void show(final String string) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                status.setText(string);
            }
        });
    }
}
